const Koa = require('koa');
const router = require('koa-router')();
const fs = require('fs')
const bodyParser = require('koa-bodyparser');
const path  = require('path')
// 创建一个Koa对象表示web app本身:
const app = new Koa();
app.use(bodyParser());

function addMapping(router, mapping) {
  for (var url in mapping) {
      if (url.startsWith('GET ')) {
          var path = url.substring(4);
          router.get(path, mapping[url]);
          console.log(`register URL mapping: GET ${path}`);
      } else if (url.startsWith('POST ')) {
          var path = url.substring(5);
          router.post(path, mapping[url]);
          console.log(`register URL mapping: POST ${path}`);
      } else {
          console.log(`invalid URL: ${url}`);
      }
  }
}

function addControllers(router) {
  var files = fs.readdirSync(path.resolve(__dirname, 'controllers'));
  console.log(files)
  var js_files = files.filter((f) => {
      return f.endsWith('.js');
  });

  for (var f of js_files) {
      console.log(`process controller: ${f}...`);
      let mapping = require(path.resolve(__dirname, 'controllers', f));
      addMapping(router, mapping);
  }
}
addControllers(router)
// add router middleware:

app.use(router.routes());
// 在端口3000监听:
app.listen(3000);
console.log('app started at port 3000...');